package com.ysy.logistics.util;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 姚斯羽
 * @date 2025/4/16 10:36
 * @description: 简单数据预测
 */
public class LinearRegression {

    public static void main(String[] args) {
// 创建训练数据
        List<Double> x = new ArrayList<>();
        List<Double> y = new ArrayList<>();
        x.add(2.0); y.add(10.0);
        x.add(4.0); y.add(20.0);
        x.add(5.0); y.add(22.0);
        x.add(7.0); y.add(30.0);
        x.add(8.0); y.add(33.0);
// 训练模型
        double[] coefficients = train(x, y);
// 预测房价
        double price = predict(coefficients, 9.0);
        System.out.println("预测：" + price);
    }
    // 训练模型
    public static double[] train(List<Double> x, List<Double> y) {
        int n = x.size();
        double xSum = 0.0, ySum = 0.0, xySum = 0.0, xxSum = 0.0;
        for (int i = 0; i < n; i++) {
            xSum += x.get(i);
            ySum += y.get(i);
            xySum += x.get(i) * y.get(i);
            xxSum += x.get(i) * x.get(i);
        }
        double xMean = xSum / n;
        double yMean = ySum / n;
        double beta1 = (xySum - n * xMean * yMean) / (xxSum - n * xMean * xMean);
        double beta0 = yMean - beta1 * xMean;
        double[] coefficients = new double[2];
        coefficients[0] = beta0;
        coefficients[1] = beta1;
        return coefficients;
    }
    // 预测
    public static double predict(double[] coefficients, double x) {
        double beta0 = coefficients[0];
        double beta1 = coefficients[1];
        return beta0 + beta1 * x;
    }
}
